package zhuzx.solution;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

import javax.swing.JOptionPane;

import org.zhuzx.util.MicroUtil;

public class PojoUtil {
	
	public static void main(String[] args) throws IllegalAccessException, InstantiationException {
		String inputValue = JOptionPane.showInputDialog("请输入类源码：");
		String code = createMapConstructor(inputValue);
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Clipboard clipboard = toolkit.getSystemClipboard();
		StringSelection ss = new StringSelection(code);
		clipboard.setContents(ss, null);
	}
	
	private static String getClassName(String classSrc) {
		String temp = MicroUtil.extractMatches(classSrc, "public class (\\w)+ ")[0];
		String className = temp.substring("public class".length()).trim();
		return className;
	}
	
	private static String createMapConstructor(String classSrc) {
		StringBuilder sb = new StringBuilder();
		String name = getClassName(classSrc);
		sb.append("\tpublic " + name + "(Map<String,String> map) {\n");
		sb.append("\t\tsuper();\n");
		String[] temps = MicroUtil.extractMatches(classSrc, "private [.\\w]+ \\w+;");
		for (int i=0; i<temps.length; i++) {
			temps[i] = temps[i].substring("private ".length(), temps[i].length()-1);
		}
		for (String temp : temps) {
			String[] words = temp.split(" ");
			String type = words[0];
			if (type.indexOf(".") >= 0) {
				String[] array = type.split("\\.");
				type = array[array.length-1];
			}
			String field = words[1];
			sb.append("\t\tif (map.get(\"" + field + "\")!=null && "
					+ "!map.get(\"" + field + "\").trim().equals(\"\")) {\n");
			
			if (type.endsWith("Timestamp")) {
				sb.append("\t\t\tif (map.get(\"" + field + "\").length() == 10) {\n");
				sb.append("\t\t\t\tmap.put(\"" + field + "\", map.get("
						+ "\"" + field + "\").replaceAll(\"/\", \"-\") + \" 00:00:00\");\n");
				sb.append("\t\t\t}\n");
			}
			if (type.endsWith("BigDecimal")) {
				sb.append("\t\t\tthis." + field + " = new " + "BigDecimal(map.get(\"" + field + "\"));\n");
			} else if (type.equals("String")) {
				sb.append("\t\t\tthis." + field + " = map.get(\"" + field + "\");\n");
			} else {
				sb.append("\t\t\tthis." + field + " = "
						+ type + ".valueOf(map.get(\"" + field + "\"));\n");
			}
			sb.append("\t\t}\n");
			System.out.println(field);
		}
		sb.append("\t}\n");
		System.out.println(sb);
		return sb.toString();
	}
	
}